package com.gl.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gl.order.entity.OrderNumberInfo;
import com.gl.order.entity.OrderSize;
import com.gl.order.entity.dto.SizeDto;
import com.gl.order.entity.vo.ChildSizeVo;
import com.gl.order.entity.vo.SizeInfoVo;
import com.gl.order.mapper.OrderNumberInfoMapper;
import com.gl.order.service.OrderNumberInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: liangSY
 * @Date: 2021/6/26
 * @ClassName: OrderNumberInfoServiceImpl
 * @Description: OrderNumberInfoServiceImpl描述
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderNumberInfoServiceImpl extends ServiceImpl<OrderNumberInfoMapper, OrderNumberInfo> implements OrderNumberInfoService {


    @Override
    public void addOrderNum(String orderId, String orderNo, List<SizeDto> list) {
        if(CollectionUtil.isEmpty(list)){
            return;
        }
        List<OrderNumberInfo> numberInfos = new ArrayList<>();
        list.stream().forEach(size -> {
            if(StringUtils.isBlank(size.getId())){
                throw  new RuntimeException("尺码数据异常，系统操作失败！");
            }
            numberInfos.add(OrderNumberInfo.builder()
                    .num(size.getNum())
                    .sizeId(size.getId())
                    .state(size.getState())
                    .productName(size.getProductName())
                    .orderId(orderId)
                    .orderNo(orderNo)
                    .build());
        });
        saveBatch(numberInfos);
    }

    @Override
    public List<SizeInfoVo> getSizeVos(List<OrderSize> sizes, String orderId) {
        LambdaQueryWrapper<OrderNumberInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(OrderNumberInfo::getOrderId,orderId);
        List<OrderNumberInfo> list = list(queryWrapper);
        List<SizeInfoVo> rel = new ArrayList<>();
        Map<String, List<OrderNumberInfo>> result = list.stream().collect(Collectors.groupingBy(
                info -> info.getProductName() + ":" +  info.getState()
        ));
        result.forEach((k, v) -> {
            String[] str = k.split(":");
            SizeInfoVo vo = new SizeInfoVo();
            vo.setProductName(str[0]);
            vo.setState(new Boolean(str[1]));
            List<ChildSizeVo> child = handleOrderNumberInfo(sizes, v);
            vo.setSizeList(child);
            vo.setNum(BigDecimal.valueOf(child.stream().mapToInt(ChildSizeVo::getNum).sum()));
            rel.add(vo);
        });
        return rel;
    }

    @Override
    public void delByOrder(String orderId) {
        LambdaQueryWrapper<OrderNumberInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(OrderNumberInfo::getOrderId,orderId);
        remove(queryWrapper);
    }

    private List<ChildSizeVo> handleOrderNumberInfo(List<OrderSize> sizes, List<OrderNumberInfo> infos){
        Map<String, Integer> map = infos.stream().collect(Collectors.toMap(OrderNumberInfo::getSizeId, OrderNumberInfo::getNum));
        List<ChildSizeVo> rel = new ArrayList<>();
        sizes.stream().forEach(size -> {
            int num = map.containsKey(size.getId()) ? map.get(size.getId()) : 0;
            ChildSizeVo sizeVo = ChildSizeVo.builder().num(num).id(size.getId()).name(size.getName()).build();
            rel.add(sizeVo);
        });
        return rel;
    }

    public List<OrderNumberInfo> getByOrderId(String orderId){
        LambdaQueryWrapper<OrderNumberInfo> queryWrapper =  Wrappers.lambdaQuery();
        queryWrapper.eq(OrderNumberInfo::getOrderId,orderId);
        List<OrderNumberInfo> list = list(queryWrapper);
        return list;
    }

}
